import 'package:flutter/material.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:ichinesereader/controller/authentication.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/exam/ExamPage.dart';
import 'package:ichinesereader/exam/apExam/BGAPExamController.dart';
import 'package:ichinesereader/exam/apExam/BGAPExamPage.dart';
import 'package:ichinesereader/exam/controllers/ExamPageController.dart';
import 'package:ichinesereader/exam/runningrecord/StudentRunningRecordController.dart';
import 'package:ichinesereader/exam/runningrecord/StudentRunningRecordPage.dart';
import 'package:ichinesereader/models/assessment/assessmentQueryDto.dart';
import 'package:ichinesereader/models/assessment/assessmentItem.dart';
import 'package:ichinesereader/models/common/assignmentState.dart';
import 'package:ichinesereader/models/teacher/TeacherAssessment.dart';
import 'package:ichinesereader/pages/teacher/assessments.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import '../../models/book/BookItem.dart';
import '../../pages/teacher/assessmentStepper.dart';
import '../../pages/teacher/evaluationRecordReview.dart';
import '../../themes/buttonStyles.dart';
import '../../themes/pageStyles.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:just_the_tooltip/just_the_tooltip.dart';

//import '../../pages/teacher/evaluationRecordReview.dart';
// import 'package:ichinesereader/pages/assessment/ibSpeaking.dart';
// import 'package:ichinesereader/pages/assessment/ibSpeakingForWeb.dart';

// ignore: must_be_immutable
class AssessmentsDataGrids extends StatelessWidget {
  AssessmentsDataGrids(this.isTeacher, this.assesssmentItems, this.showMenu);

  List<AssessmentItem> assesssmentItems;
  bool isTeacher = false;
  bool showMenu = false;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];
  AppButtonStyles _appButtonStyles = new AppButtonStyles();
  DataGridController _dataGridController = DataGridController();
  final AssessmentsController _assessmentsController = Get.find();
  final PageStyles _pageStyles = PageStyles();
  var box = Hive.box('appconfig');

  @override
  Widget build(BuildContext context) {
    Log.debug('build AssessmentsDataGrids');
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;

    return Column(children: [
      Visibility(
        visible: showMenu,
        //左侧椭圆形选项背景
        child: IntrinsicHeight(
          child: isSmallScreen
              ? Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(
                        top: 9.0,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          ElevatedButton(
                              style: _appButtonStyles.createButtonStyle(),
                              child: Text(
                                'Create'.tr,
                              ),
                              onPressed: () {
                                teacherAssessmentTabController.index = 1;
                                // teacherAssessmentPageKey
                                //     .currentState?.tabController.index = 1;
                              }),
                          Padding(
                            padding:
                                const EdgeInsets.symmetric(horizontal: 6.0),
                            child: ElevatedButton(
                                style: _appButtonStyles.duplicateButtonStyle(),
                                child: Text(
                                  'Duplicate'.tr,
                                ),
                                onPressed: () {
                                  if (this
                                          ._dataGridController
                                          .selectedRows
                                          .length >
                                      0) {
                                    var _selectedRow = this
                                        ._dataGridController
                                        .selectedRows[0];
                                    var qid = _selectedRow
                                        .getCells()
                                        .where((element) =>
                                            element.columnName == 'Id')
                                        .first
                                        .value;
                                    var qtype = _selectedRow
                                        .getCells()
                                        .where((element) =>
                                            element.columnName == 'Type')
                                        .first
                                        .value;
                                    var _assessment = assesssmentItems
                                        .where((element) =>
                                            element.assessmentId == qid)
                                        .first;
                                    List<BookItem> bookitems = [];
                                    if (_assessment.questionGroup != null) {
                                      BookItem item = new BookItem();
                                      var questionGroup =
                                          _assessment.questionGroup;
                                      item.bookId = questionGroup?.bookId;
                                      item.bookImageLink =
                                          questionGroup?.imageLink;
                                      item.bookTitle = questionGroup?.title;
                                      item.bookContentLink = questionGroup?.id;
                                      bookitems.add(item);
                                      Get.to(() => AssessmentSteps(
                                            isNew: false,
                                            books: bookitems,
                                            assessmentItem: _assessment,
                                            type: qtype,
                                            //assessmentId: qid
                                          ));
                                    }
                                  }
                                }),
                          ),
                          ElevatedButton(
                              style: ButtonStyle(
                                backgroundColor: Get.isDarkMode
                                    ? MaterialStateProperty.all(
                                        Get.theme.primaryColorDark,
                                      )
                                    : MaterialStateProperty.all(
                                        AppTheme.colors.deleteBtn,
                                      ),
                              ),
                              child: Text('Delete'.tr,
                                  style: TextStyle(
                                    fontFamily: 'Montserrat',
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : AppTheme.colors.lightPink,
                                    fontSize: 16.0,
                                  )),
                              onPressed: () {
                                if (this
                                        ._dataGridController
                                        .selectedRows
                                        .length >
                                    0) {
                                  var _selectedRow =
                                      this._dataGridController.selectedRows[0];
                                  var assessmentId = _selectedRow
                                      .getCells()
                                      .where((element) =>
                                          element.columnName == 'Id')
                                      .first
                                      .value;
                                  var status = _selectedRow
                                      .getCells()
                                      .where((element) =>
                                          element.columnName == 'Status')
                                      .first
                                      .value;
                                  if (status == 'QUEUED') {
                                    _assessmentsController
                                        .deleteAssessmentByAssessmentId(
                                            assessmentId)
                                        .then((statusMessage) {
                                      if (statusMessage.status == 1000) {
                                        showSnackMsg('Assessment deleted!');
                                      } else {
                                        showSnackMsg(
                                            'Failed to delete assessment!');
                                      }
                                    });
                                  } else {
                                    showSnackMsg(
                                        'Only queued assessments can be deleted!');
                                  }
                                }
                              }),
                        ],
                      ),
                    ),
                    FormBuilderChoiceChip(
                      decoration: InputDecoration(
                        border: InputBorder.none,
                      ),
                      alignment: WrapAlignment.end,
                      spacing: 3.0,
                      backgroundColor: Get.isDarkMode
                          ? Theme.of(context).primaryColor
                          : Colors.grey,
                      selectedColor: Get.isDarkMode
                          ? (Colors.white)
                          : AppTheme.colors.orangeBtn,
                      name: 'assessment_state_chip',
                      onChanged: (value) {
                        if (value == null) return;
                        AssessmentQueryDto dto = new AssessmentQueryDto();
                        dto.live = false;
                        dto.past = false;
                        dto.queued = false;
                        var item = value as AssignmentState;
                        if (item.value == 'live') dto.live = true;
                        if (item.value == 'past') dto.past = true;
                        if (item.value == 'queued') dto.queued = true;

                        // String _classId =
                        //     _userController.currentClass.value.classId.toString();
                        String _classId = box.get(
                                CacheManagerKey['currentclass'].toString()) ??
                            '';
                        if (_classId != '')
                          _assessmentsController.fetchAssessmentsByClass(
                              _classId, dto);
                      },
                      initialValue: [
                        AssignmentState(value: 'live', label: 'OPEN')
                      ],
                      options: Constants.assignmentStateOptions
                          .map(
                              (state) => FormBuilderChipOption<AssignmentState>(
                                    value: state,
                                    child: Text(
                                      state.label.toString().tr,
                                      style: TextStyle(
                                          color: Get.isDarkMode
                                              ? Colors.black
                                              : AppTheme.colors.lightOrange),
                                    ),
                                  ))
                          .toList(),
                    ),
                    //右侧按钮群
                  ],
                )
              : Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      //椭圆形选
                      child: FormBuilderChoiceChip(
                        decoration: InputDecoration(
                          border: InputBorder.none,
                        ),
                        spacing: 3.0,
                        backgroundColor: Get.isDarkMode
                            ? Theme.of(context).primaryColor
                            : Colors.grey,
                        selectedColor: Get.isDarkMode
                            ? (Colors.white)
                            : AppTheme.colors.orangeBtn,
                        name: 'assessment_state_chip',
                        onChanged: (value) {
                          if (value == null) return;
                          AssessmentQueryDto dto = new AssessmentQueryDto();
                          dto.live = false;
                          dto.past = false;
                          dto.queued = false;
                          var item = value as AssignmentState;
                          if (item.value == 'live') dto.live = true;
                          if (item.value == 'past') dto.past = true;
                          if (item.value == 'queued') dto.queued = true;

                          // String _classId =
                          //     _userController.currentClass.value.classId.toString();
                          String _classId = box.get(
                                  CacheManagerKey['currentclass'].toString()) ??
                              '';
                          if (_classId != '')
                            _assessmentsController.fetchAssessmentsByClass(
                                _classId, dto);
                        },
                        initialValue: [
                          AssignmentState(value: 'live', label: 'OPEN')
                        ],
                        options: Constants.assignmentStateOptions
                            .map((state) =>
                                FormBuilderChipOption<AssignmentState>(
                                  value: state,
                                  child: Text(
                                    state.label.toString().tr,
                                    style: TextStyle(
                                        color: Get.isDarkMode
                                            ? Colors.black
                                            : AppTheme.colors.lightOrange),
                                  ),
                                ))
                            .toList(),
                      ),
                    ),
                    //右侧按钮群
                    Padding(
                      padding: const EdgeInsets.only(top: 9.0, right: 9.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          ElevatedButton(
                              style: _appButtonStyles.createButtonStyle(),
                              child: Text(
                                'Create'.tr,
                                style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : Get.theme.primaryColorLight),
                              ),
                              onPressed: () {
                                teacherAssessmentTabController.index = 1;
                                // teacherAssessmentPageKey
                                //     .currentState?.tabController.index = 1;
                              }),
                          Padding(
                            padding:
                                const EdgeInsets.symmetric(horizontal: 6.0),
                            child: ElevatedButton(
                                style: _appButtonStyles.duplicateButtonStyle(),
                                child: Text(
                                  'Duplicate'.tr,
                                  style: TextStyle(
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Get.theme.primaryColorLight),
                                ),
                                onPressed: () {
                                  if (this
                                          ._dataGridController
                                          .selectedRows
                                          .length >
                                      0) {
                                    var _selectedRow = this
                                        ._dataGridController
                                        .selectedRows[0];
                                    var qid = _selectedRow
                                        .getCells()
                                        .where((element) =>
                                            element.columnName == 'Id')
                                        .first
                                        .value;
                                    var qtype = _selectedRow
                                        .getCells()
                                        .where((element) =>
                                            element.columnName == 'Type')
                                        .first
                                        .value;
                                    var _assessment = assesssmentItems
                                        .where((element) =>
                                            element.assessmentId == qid)
                                        .first;
                                    List<BookItem> bookitems = [];
                                    if (_assessment.questionGroup != null) {
                                      BookItem item = new BookItem();
                                      var questionGroup =
                                          _assessment.questionGroup;
                                      item.bookId = questionGroup?.bookId;
                                      item.bookImageLink =
                                          questionGroup?.imageLink;
                                      item.bookTitle = questionGroup?.title;
                                      item.bookContentLink = questionGroup?.id;
                                      bookitems.add(item);
                                      Get.to(() => AssessmentSteps(
                                            isNew: false,
                                            books: bookitems,
                                            assessmentItem: _assessment,
                                            type: qtype,
                                            //assessmentId: qid
                                          ));
                                    }
                                  }
                                }),
                          ),
                          ElevatedButton(
                              style: ButtonStyle(
                                backgroundColor: Get.isDarkMode
                                    ? MaterialStateProperty.all(
                                        Get.theme.primaryColorDark,
                                      )
                                    : MaterialStateProperty.all(
                                        AppTheme.colors.deleteBtn,
                                      ),
                              ),
                              child: Text('Delete'.tr,
                                  style: TextStyle(
                                    fontFamily: 'Montserrat',
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : AppTheme.colors.lightPink,
                                    fontSize: 16.0,
                                  )),
                              onPressed: () {
                                if (this
                                        ._dataGridController
                                        .selectedRows
                                        .length >
                                    0) {
                                  var _selectedRow =
                                      this._dataGridController.selectedRows[0];
                                  var assessmentId = _selectedRow
                                      .getCells()
                                      .where((element) =>
                                          element.columnName == 'Id')
                                      .first
                                      .value;
                                  var status = _selectedRow
                                      .getCells()
                                      .where((element) =>
                                          element.columnName == 'Status')
                                      .first
                                      .value;
                                  if (status == 'QUEUED') {
                                    _assessmentsController
                                        .deleteAssessmentByAssessmentId(
                                            assessmentId)
                                        .then((statusMessage) {
                                      if (statusMessage.status == 1000) {
                                        showSnackMsg('Assessment deleted!');
                                      } else {
                                        showSnackMsg(
                                            'Failed to delete assessment!');
                                      }
                                    });
                                  } else {
                                    showSnackMsg(
                                        'Only queued assessments can be deleted!');
                                  }
                                }
                              }),
                        ],
                      ),
                    ),
                  ],
                ),
        ),
      ),
      Expanded(child: _buildAssessmentDataGrid()),
    ]);
  }

//列表
  Container _buildAssessmentDataGrid() {
    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12.0),
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source: AssessmentDataGridSource(items: assesssmentItems),
          isScrollbarAlwaysShown: true,
          controller: _dataGridController,
          showCheckboxColumn: isTeacher ? true : false,
          checkboxColumnSettings: Get.isDarkMode
              ? DataGridCheckboxColumnSettings(
                  backgroundColor: Color(0xff0a0e21),
                )
              : DataGridCheckboxColumnSettings(
                  backgroundColor: Colors.blue[50]),
          allowSorting: true,
          allowFiltering: true,
          allowTriStateSorting: true,
          allowSwiping: isTeacher ? true : false,
          selectionMode:
              isTeacher ? SelectionMode.multiple : SelectionMode.none,
          navigationMode: GridNavigationMode.row,
          endSwipeActionsBuilder:
              (BuildContext context, DataGridRow row, int rowIndex) {
            if (isTeacher) {
              return GestureDetector(
                  onTap: () {
                    var assessmentId = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    var status = row
                        .getCells()
                        .where((element) => element.columnName == 'Status')
                        .first
                        .value;
                    if (status == 'QUEUED') {
                      _assessmentsController
                          .deleteAssessmentByAssessmentId(assessmentId);
                      showSnackMsg('Assessment deleted!');
                    } else {
                      showSnackMsg('Only queued assessments can be deleted!');
                    }
                  },
                  child: Container(
                      color: Colors.redAccent,
                      child: Center(
                        child: Icon(Icons.delete),
                      )));
            } else {
              return null;
            }
          },
          columns: <GridColumn>[
            GridColumn(
              width: isWebOrDesktop ? 220 : 180,
              columnName: 'Title',
              label: buildDataGridColumnLabel('Title'),
            ),
            GridColumn(
              columnName: 'Type',
              allowFiltering: true,
              width: isWebOrDesktop ? 180 : 180,
              label: buildDataGridColumnLabel('Type'),
            ),
            GridColumn(
              columnName: 'Status',
              allowFiltering: false,
              width: isWebOrDesktop ? 160 : 140,
              label: buildDataGridColumnLabel('Status'),
            ),
            GridColumn(
              columnName: 'Text',
              allowFiltering: false,
              width: isWebOrDesktop ? 150.0 : 120.0,
              label: buildDataGridColumnLabel('Text'),
            ),
            GridColumn(
              columnName: 'Audio',
              allowFiltering: false,
              width: isWebOrDesktop ? 150.0 : 120.0,
              label: buildDataGridColumnLabel('Audio'),
            ),
            GridColumn(
              columnName: 'CreateDate',
              allowFiltering: false,
              width: 150,
              //visible: isTeacher ? false : true,
              visible: false,
              label: buildDataGridColumnLabel('CreateDate'),
            ),
            GridColumn(
              columnName: 'Students',
              allowFiltering: false,
              width: 150,
              visible: false,
              label: buildDataGridColumnLabel('Students'),
            ),
            GridColumn(
              columnName: 'StartDate',
              allowFiltering: false,
              width: 180,
              visible: isTeacher ? true : false,
              label: buildDataGridColumnLabel('StartDate'),
            ),
            GridColumn(
              columnName: 'DueDate',
              allowFiltering: false,
              width: 180,
              label: buildDataGridColumnLabel('DueDate'),
            ),
            GridColumn(
              columnName: 'Id',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
          ],
        ),
      ),
    );
  }
}

class AssessmentDataGridSource extends DataGridSource {
  AssessmentDataGridSource({required List<AssessmentItem> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                columnName: 'Title',
                value: dataGridRow.name,
              ),
              DataGridCell<String>(columnName: 'Type', value: dataGridRow.type),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.status?.toUpperCase()),
              DataGridCell<String>(
                  columnName: 'Text', value: dataGridRow.textType),
              DataGridCell<String>(
                  columnName: 'Audio', value: dataGridRow.audioType),
              DataGridCell<List<StudentA>>(
                  columnName: 'Students',
                  value: dataGridRow.students ?? <StudentA>[]),
              DataGridCell<DateTime>(
                  columnName: 'CreateDate', value: dataGridRow.startDate),
              DataGridCell<DateTime>(
                  columnName: 'StartDate', value: dataGridRow.commitDate),
              DataGridCell<DateTime>(
                  columnName: 'DueDate', value: dataGridRow.dueDate),
              DataGridCell<String>(
                  columnName: 'Id', value: dataGridRow.assessmentId),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;
  final LoginController _loginController = Get.find();
  final AssessmentsController _assessmentsController = Get.find();

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    String studentNames = '';
    List<StudentA> students = row
        .getCells()
        .where((element) => element.columnName == 'Students')
        .first
        .value;
    if (students.isNotEmpty) {
      students.forEach((s) {
        studentNames = studentNames +
            s.lastName.toString() +
            ' ' +
            s.firstName.toString() +
            ', ';
      });

      if (studentNames.length > 2) {
        studentNames = studentNames.substring(0, studentNames.length - 2);
      }
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Title') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                //此处改动不对，需要对老师和学生角色功能区分
                // child: GestureDetector(
                //     onTap: () {
                //       var qid = row
                //           .getCells()
                //           .where((element) => element.columnName == 'Id')
                //           .first
                //           .value;
                //       var qtype = row
                //           .getCells()
                //           .where((element) => element.columnName == 'Type')
                //           .first
                //           .value;
                //       var _assessment = _assessmentsController.assessItemsForTeacher
                //           .where((element) => element.assessmentId == qid)
                //           .first;
                //       List<BookItem> bookitems = [];
                //       if (_assessment.questionGroup != null) {
                //         BookItem item = new BookItem();
                //         var questionGroup = _assessment.questionGroup;
                //         item.bookId = questionGroup?.bookId;
                //         item.bookImageLink = questionGroup?.imageLink;
                //         item.bookTitle = questionGroup?.title;
                //         bookitems.add(item);
                //         Get.to(() => AssessmentSteps(
                //             isNew: false,
                //             books: bookitems,
                //             assessmentItem: _assessment,
                //             type: qtype,
                //             assessmentId: qid,
                //             from: 'edit'));
                //       }
                //     },
                //     child: Text(
                //       dataGridCell.value.toString(),
                //       style: Get.textTheme.titleLarge,
                //       //style: TextStyle(color: Colors.blue[300], fontWeight: FontWeight.bold),
                //       overflow: TextOverflow.ellipsis,
                //     )),

                child: GestureDetector(
                  onTap: () {
                    var qid = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    var qtype = row
                        .getCells()
                        .where((element) => element.columnName == 'Type')
                        .first
                        .value;
                    var qname = row
                        .getCells()
                        .where((element) => element.columnName == 'Title')
                        .first
                        .value;

                    //handling for student role
                    if (_loginController.getRole() ==
                        Constants.NanhaiRole_Student) {
                      if (GetPlatform.isWeb) {
                        if (qtype == Constants.AssessmentType_Running_Record) {
                          // migration test new running records
                          //  Get.to(() => InAppWebViewAppRunningRecordScreen(
                          //        assessmentId: qid,
                          //        userName: _loginController.getUsername(),
                          //      ));
                          // launchInWebViewWithJavaScript(
                          //     '${Constants.BaseURL}running-record/student/$qid/${_loginController.getUsername()}');
                          Get.lazyPut(() => StudentRunningRecordController());
                          Get.to(() => StudentRunningRecordPage(
                              assessmentId: qid,
                              username: _loginController.getUsername() ??
                                  ''))?.then((value) =>
                              _assessmentsController.fetchStudentAssessments());
                        } else if (qtype == Constants.AssessmentType_AP) {
                          var assessment = _assessmentsController.assessItems
                              .where((element) => element.assessmentId == qid)
                              .first;
                          String? questionGroupId = '';
                          if (assessment.assessmentId != null) {
                            questionGroupId = assessment.questionGroup?.id;
                          }
                          Get.lazyPut(() => BGAPExamController());
                          Get.to(() => BGAPExamPage(), arguments: {
                            'id': qid,
                            'questionGroupId': questionGroupId,
                            'questionTitle':qname,
                            'userName': _loginController.getUsername()
                          })?.then((value) =>
                              _assessmentsController.fetchStudentAssessments());
                        } else {
                          /// 引入exam
                          var assessment = _assessmentsController.assessItems
                              .where((element) => element.assessmentId == qid)
                              .first;
                          String? questionGroupId = '';
                          if (assessment.assessmentId != null) {
                            questionGroupId = assessment.questionGroup?.id;
                          }
                          Get.lazyPut(() => ExamPageController());
                          Get.to(() => ExamPage(), arguments: {
                            'id': qid,
                            'questionGroupId': questionGroupId,
                            'questionTitle': qname,
                            'userName': _loginController.getUsername()
                          })?.then((value) =>
                              _assessmentsController.fetchStudentAssessments());
                          // Get.lazyPut(() => BGQuizController());
                          // Get.to(() => BGQuizPage(assessmentId: qid, username: _loginController.getUsername()??''))
                          //     ?.then((value) => _assessmentsController.fetchStudentAssessments());
                        }
                      } else //when not web
                      {
                        if (qtype == Constants.AssessmentType_Running_Record) {
                          Get.lazyPut(() => StudentRunningRecordController());
                          Get.to(() => StudentRunningRecordPage(
                              assessmentId: qid,
                              username: _loginController.getUsername() ??
                                  ''))?.then((value) =>
                              _assessmentsController.fetchStudentAssessments());
                        } else if (qtype == Constants.AssessmentType_AP) {
                          var assessment = _assessmentsController.assessItems
                              .where((element) => element.assessmentId == qid)
                              .first;
                          String? questionGroupId = '';
                          if (assessment.assessmentId != null) {
                            questionGroupId = assessment.questionGroup?.id;
                          }
                          Get.lazyPut(() => BGAPExamController());
                          Get.to(() => BGAPExamPage(), arguments: {
                            'id': qid,
                            'questionGroupId': questionGroupId,
                            'questionTitle':qname,
                            'userName': _loginController.getUsername()
                          })?.then((value) =>
                              _assessmentsController.fetchStudentAssessments());
                        } else {
                          /// 引入exam
                          var assessment = _assessmentsController.assessItems
                              .where((element) => element.assessmentId == qid)
                              .first;
                          String? questionGroupId = '';
                          if (assessment.assessmentId != null) {
                            questionGroupId = assessment.questionGroup?.id;
                          }
                          Get.lazyPut(() => ExamPageController());
                          Get.to(() => ExamPage(), arguments: {
                            'id': qid,
                            'questionGroupId': questionGroupId,
                            'questionTitle': qname,
                            'userName': _loginController.getUsername()
                          })?.then((value) =>
                              _assessmentsController.fetchStudentAssessments());
                          // Get.lazyPut(() => BGQuizController());
                          // Get.to(() => BGQuizPage(assessmentId: qid, username: _loginController.getUsername()??''))
                          //     ?.then((value) => _assessmentsController.fetchStudentAssessments());
                        }
                      }
                    }
                    //handling for teacher role
                    else if (_loginController.getRole() ==
                        Constants.NanhaiRole_Teacher) {
                      var _assessment = _assessmentsController
                          .assessItemsForTeacher
                          .where((element) => element.assessmentId == qid)
                          .first;

                      List<BookItem> bookitems = [];
                      if (_assessment.questionGroup != null) {
                        BookItem item = new BookItem();
                        var questionGroup = _assessment.questionGroup;
                        item.bookId = questionGroup?.bookId;
                        item.bookImageLink = questionGroup?.imageLink;
                        item.bookTitle = questionGroup?.title;
                        bookitems.add(item);
                        Get.to(() => AssessmentSteps(
                            isNew: false,
                            books: bookitems,
                            assessmentItem: _assessment,
                            type: qtype,
                            assessmentId: qid,
                            from: 'edit'));
                      }

                      // if (GetPlatform.isWeb) {
                      //   // need add code for teacher on macos and web
                      //   // 老师账户这里是对assessment的浏览或者其它处理

                      // } else {
                      //   var qid = row
                      //       .getCells()
                      //       .where((element) => element.columnName == 'Id')
                      //       .first
                      //       .value;
                      //   var qtype = row
                      //       .getCells()
                      //       .where((element) => element.columnName == 'Type')
                      //       .first
                      //       .value;
                      //   var assessment = _assessmentsController.assessItems
                      //       .where((element) => element.assessmentId == qid)
                      //       .first;
                      //   // if (assessment.assessmentId != null) {
                      //   //   AssessmentEditDto assessmentDto =
                      //   //       new AssessmentEditDto();
                      //   //   QuestionGroupId questionGroupId = new QuestionGroupId();
                      //   //   questionGroupId.id = assessment.questionGroup?.id;
                      //   //   questionGroupId.title = assessment.questionGroup?.title;

                      //   //   assessmentDto.operationType = 'view';
                      //   //   assessmentDto.id = qid;
                      //   //   assessmentDto.instruction = assessment.instructions;
                      //   //   assessmentDto.assessmentName = assessment.name;
                      //   //   assessmentDto.audioType = assessment.audioType;
                      //   //   assessmentDto.questionGroupIds = [questionGroupId];
                      //   //   assessmentDto.startDate =
                      //   //       assessment.startDate.toString();
                      //   //   assessmentDto.dueDate = assessment.dueDate.toString();
                      //   //   assessmentDto.textType = assessment.textType;
                      //   //   assessmentDto.type = new Type();

                      //   //   if (qtype.toString().contains('IBDP')) {
                      //   //     assessmentDto.type?.label = 'IB Speaking';
                      //   //     assessmentDto.type?.value = 'IB_SPEAKING';
                      //   //   }
                      //   //   if (qtype.toString().contains('RUNNING')) {
                      //   //     assessmentDto.type?.label = 'Running Record';
                      //   //     assessmentDto.type?.value = 'RUNNING_RECORD';
                      //   //   }
                      //   //   assessmentDto.studentUserNames = [];
                      //   //   assessment.students?.forEach((element) {
                      //   //     Type item = new Type();
                      //   //     item.value = element.userName;
                      //   //     item.label =
                      //   //         '${element.firstName} ${element.lastName}';
                      //   //     assessmentDto.studentUserNames?.add(item);
                      //   //   });

                      //   //   // 老师账户这里是对assessment的浏览或者其它处理

                      //   //   // Get.to(() => InAppWebViewTeacherCreateAssessmentScreen(
                      //   //   //       isNew: false,
                      //   //   //       assessmentType: qtype,
                      //   //   //       operation: 'view',
                      //   //   //       assessmentEditDto: assessmentDto,
                      //   //   //     ));
                      //   // }
                      // }
                    }
                  },
                  child:
                      _loginController.getRole() == Constants.NanhaiRole_Teacher
                          ? JustTheTooltip(
                              backgroundColor: Get.isDarkMode
                                  ? Get.theme.primaryColorDark
                                  : Get.theme.primaryColorLight,
                              preferredDirection: AxisDirection.right,
                              elevation: 4.0,
                              content: Container(
                                padding: EdgeInsets.all(8.0),
                                width: 480,
                                color: Colors.transparent,
                                child: Text(
                                  studentNames,
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : Colors.black87,
                                  ),
                                ),
                              ),
                              child: Text(
                                dataGridCell.value.toString(),
                                style: Get.theme.textTheme.titleLarge,
                                overflow: TextOverflow.ellipsis,
                              ),
                            )
                          : Text(
                              dataGridCell.value.toString(),
                              style: Get.theme.textTheme.titleLarge,
                              overflow: TextOverflow.ellipsis,
                            ),
                ));
          } else if (dataGridCell.columnName == 'CreateDate' ||
              dataGridCell.columnName == 'StartDate' ||
              dataGridCell.columnName == 'DueDate') {
            if (dataGridCell.value != null) {
              return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 6.0),
                child: Text(
                  DateFormat('yyyy-MM-dd kk:mm').format(dataGridCell.value),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ),
              );
            } else {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    ' - ',
                    overflow: TextOverflow.ellipsis,
                  ));
            }
          } else if (dataGridCell.columnName == 'Status') {
            String _status = dataGridCell.value
                .toString()
                .replaceAll('LIVE', 'OPEN')
                .replaceAll('PAST', 'CLOSED')
                .replaceAll('COMPLETED', 'CLOSED');
            if (_loginController.getRole() == Constants.NanhaiRole_Teacher) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: GestureDetector(
                      onTap: () {
                        if (_loginController.getRole() ==
                            Constants.NanhaiRole_Teacher) {
                          var type = row
                              .getCells()
                              .where((element) => element.columnName == 'Type')
                              .first
                              .value;
                          var qid = row
                              .getCells()
                              .where((element) => element.columnName == 'Id')
                              .first
                              .value;
                          var title = row
                              .getCells()
                              .where((element) => element.columnName == 'Title')
                              .first
                              .value;
                          if (type != Constants.AssessmentType_Running_Record) {
                            var assessment = _assessmentsController
                                .assessItemsForTeacher
                                .where((element) => element.assessmentId == qid)
                                .first;
                            if (assessment.assessmentId != null) {
                              String bookId =
                                  assessment.questionGroup?.bookId ?? '';
                              if (bookId.isNotEmpty) {
                                _assessmentsController
                                    .fetchQuestionGroupByBookCode(bookId);
                                Get.to(() => EvaluationRecordReviewPage(),
                                    arguments: {
                                      'title': title,
                                      'status': 'NEW'
                                    });
                              }
                            }
                          }
                        }
                      },
                      child: Text(
                        _status,
                        overflow: TextOverflow.ellipsis,
                        style: Get.theme.textTheme.titleLarge,
                      )));
            } else {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    _status,
                    softWrap: true,
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall,
                  ));
            }
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
